package com.gomore.opple.module.main.home;

import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.remote.retrofit.HttpResponseFunc;
import com.gomore.opple.data.remote.retrofit.RxSubscriber;
import com.gomore.opple.data.remote.retrofit.ServerResponseFunc;
import com.gomore.opple.exception.ApiException;
import com.gomore.opple.rest.common.DataPage;
import com.gomore.opple.rest.consumer.ConsumerDesigner;
import com.gomore.opple.rest.consumer.ConsumerDesignerPageResult;
import com.gomore.opple.rest.consumer.ConsumerPageResult;
import com.gomore.opple.rest.consumer.ConsumerQueryCondition;
import com.gomore.opple.rest.employee.LoginResult;
import com.gomore.opple.web.cgform.resellerstore.entity.TOResellerstoreEntity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by asus on 2016/12/27.
 */
public class HomePresenter implements HomeContract.Presenter {
    private DataRepository mDataRepositroy;
    private final HomeContract.View mView;
    private CompositeSubscription mSubscriptions;
    private List<ConsumerDesigner> consumerEntities = new ArrayList<>();
    private int rows = GlobalConstant.PAGE_SIZE;
    private int page = GlobalConstant.PAGE_START;

    @Inject
    HomePresenter(DataRepository dataRepository, HomeContract.View view) {
        mDataRepositroy = dataRepository;
        mView = view;
        mSubscriptions = new CompositeSubscription();
        mView.setPresenter(this);
    }

    @Override
    public void prepareInitData() {

    }

    @Override
    public void getConsumer(final String mobile, final boolean loadMore, final boolean showDialog) {
        if (loadMore) {
            page++;
        } else {
            page = GlobalConstant.PAGE_START;
        }
        mView.showProgressDialog();
        ConsumerQueryCondition consumerQueryCondition = new ConsumerQueryCondition();
        consumerQueryCondition.setMobileEquals(mobile);
        consumerQueryCondition.setNameEquals(mobile);
        consumerQueryCondition.setResellerCodeEquals(mDataRepositroy.getUser().getEmployee().getCurrentDepart().getOrgCode());
        DataPage dataPage = new DataPage();
        dataPage.setRows(rows);
        dataPage.setPage(page);
        consumerQueryCondition.setPage(dataPage);
        mSubscriptions.clear();
        Subscription subscription = mDataRepositroy.getConsumer(consumerQueryCondition)
                .map(new ServerResponseFunc<ConsumerDesignerPageResult>())
                .onErrorResumeNext(new HttpResponseFunc<ConsumerDesignerPageResult>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<ConsumerDesignerPageResult>() {
                    @Override
                    public void onNext(ConsumerDesignerPageResult consumerPageResult) {
                        super.onNext(consumerPageResult);
                        mView.hideProgressDialog();
                        if (loadMore) {
                            mView.showLoadMoreCompleted();
                        } else {
                            consumerEntities.clear();
                            mView.showRefreshCompleted();
                        }
                        if (consumerPageResult.getPage() <= consumerPageResult.getTotalpages()) {
                            consumerEntities.addAll(consumerPageResult.getResults());
                        }
                        mView.showContent();
                        //展示对话框
                        if (showDialog) {
                            LoginResult loginResult = mDataRepositroy.getUser();
                            if (loginResult.getStoreCode() == null) {
                                //展示保存门店代码
                                mView.showDialog();
                            } else {
                                if (!loginResult.getIsHasStoreAddress()) {
                                    //展示保存门店默认地址
                                    mView.goToAddressDialog(loginResult.getStoreCode());
                                }
                            }
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        if (loadMore) {
                            mView.showLoadMoreCompleted();
                        } else {
                            mView.showRefreshCompleted();
                        }
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public List<ConsumerDesigner> getData() {
        return consumerEntities;
    }

    @Override
    public void saveTime(String consumerId) {
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.saveLastVisitedTime(consumerId)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String string) {
                        super.onNext(string);
                        mView.hideProgressDialog();
                        mView.reflashView();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void saveStoreCode(final String storeCode) {
        TOResellerstoreEntity toResellerstoreEntity = new TOResellerstoreEntity();
        toResellerstoreEntity.setCreateDate(new Date());
        toResellerstoreEntity.setStorecode(storeCode);
        toResellerstoreEntity.setResellerid(mDataRepositroy.getUser().getEmployee().getCurrentDepart().getId());
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.saveResellerStore(toResellerstoreEntity)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String string) {
                        super.onNext(string);
                        mView.hideProgressDialog();
                        LoginResult loginResult = mDataRepositroy.getUser();
                        if (!loginResult.getIsHasStoreAddress()) {
                            mView.goToAddressDialog(storeCode);
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.clear();
    }
}
